package org.ezplatform.office.questionnaire.service;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.questionnaire.dao.QusetionnaireAnswerStatusDao;
import org.ezplatform.office.questionnaire.entity.Questionnaire;
import org.ezplatform.office.questionnaire.entity.QuestionnaireRankingExport;
import org.ezplatform.office.questionnaire.entity.QusetionnaireAnswerStatus;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.ValidateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <br> 问卷状态接口类
 * <br> 创建时间 2017-11-23
 * @author wujs
 * @version 1.0
 * 
*/
@Service("questionnaireAnswerStatusService")
@Transactional
public class QuestionnaireAnswerStatusService extends BaseService<QusetionnaireAnswerStatus,String>{
	
	@Autowired
	@Qualifier("qusetionnaireAnswerStatusDao")
	private QusetionnaireAnswerStatusDao answerStatusDao;
	@Lazy
	@Autowired
	@Qualifier("questionnaireAnswerService")
	private QuestionnaireAnswerService answerService;
	@Lazy
	@Autowired
	private QuestionnaireAnswerStatusService statusService;
	
	@Override
	protected JpaBaseDao<QusetionnaireAnswerStatus, String> getEntityDao() {
		return answerStatusDao;
	}
	
	/**
	 * 查询用户问卷状态
	 * @param userId 用户ID
	 * @param quesId 答卷ID
	 * @return 问卷状态实体
	 */
	public QusetionnaireAnswerStatus findAnswerStatus(String userId ,String quesId){
		return answerStatusDao.findAnswerStatus(userId,quesId);
	}
	
	/**
	 * 获取问卷某个状态个数
	 * @param quesId 问卷ID
	 * @param status 状态：0-关闭、1-开启、2-未开启
	 * @return 问卷某个状态个数
	 */
	public int getAnswerNum(String quesId,String status){
		List<QusetionnaireAnswerStatus> list = answerStatusDao.getAnswerStatus(status, quesId);
		int num =0;
		if(list !=null){
			num=list.size();
		}
		return num;
	}
	
	/**
	 * 获取问卷某个状态个数（优化后方法）
	 * @param quesId 问卷ID
	 * @param status 状态：0-关闭、1-开启、2-未开启
	 * @return 问卷某个状态个数
	 */
	public int getAnswerNumByQuesId(String quesId,String status) {
		return answerStatusDao.getAnswerNumByQuesId(status,quesId);
	}
	
	/**
	 * 根据问卷id删除答卷状态
	 * @param list 问卷id集合
	 * @return 删除答卷状态表个数
	 */
	public int deleteStatusByQuesId(String id){
		return answerStatusDao.deleteStatusByQuesId(id);
	}
	
	/**
	 * 根据问卷id删除答卷状态
	 * @param list 问卷id集合
	 * @return 删除答卷状态表个数
	 */
	public int deleteStatusByQuesId(List<String> list){
		return answerStatusDao.deleteStatusByQuesId(list);
	}
	
	/**
	 * 更新问卷状态表状态
	 * @param id 问卷状态id
	 * @param status 问卷状态：0-关闭、1-开启、2-未开启
	 * @return 更新问卷状态表状态个数
	 */
	public int updateStatus(List id,String status){
		return answerStatusDao.updateStatusById(status,id);
	}
	
	public List<QusetionnaireAnswerStatus> findByIds(List<String> ids){
		return answerStatusDao.findByIds(ids);
	}
	
	/**
	 * 回退答卷
	 * @param backReason 回退原因
	 * @param ids
	 * @return
	 */
	public int replyQusetionnaireByIds(String backReason, List<String> ids) {
		return answerStatusDao.replyQusetionnaireByIds(backReason, ids);
	}
	
	/**
	 * 将草稿状态的答卷变成提交
	 * @param quesId 问卷ID
	 * @return 草稿状态的答卷变成提交状态个数
	 */
	public int updateStatusToSubmit(String quesId){
		return answerStatusDao.updateStatusToSubmit(quesId);
	}
	
	/**
	 * 当问卷结束时间小于当前时间将草稿状态的答卷变成提交
	 * @return 问卷结束时间小于当前时间将草稿状态的答卷变成提交个数
	 */
	public int updateStatusToSubmitByDate(){
		return answerStatusDao.updateStatusToSubmitByDate();
	}
	
	public int getAnswerNumByQuesId(String quesId) {
		return answerStatusDao.getAnswerNumByQuesId(quesId);
	}
	
	/**
	 * 根据成绩排名
	 * @param quesId
	 */
	public void rankingByGrade(String quesId) {
		List<QusetionnaireAnswerStatus> list = answerStatusDao.findAnswerStatusListGradeDesc(quesId);
		if(CollectionUtils.isNotEmpty(list)) {
			int ranking = 1;
			QusetionnaireAnswerStatus qs = null;
			for(int i = 0; i < list.size(); i++) {
				qs = list.get(i);
				if(i > 0) {
					if(qs.getGrade() != list.get(i - 1).getGrade()) 
						ranking++;
					qs.setRanking(ranking);
				}
				qs.setRanking(ranking);
			}
		}
		this.save(list);
	}
	
	/**
	 * 获取成绩排名
	 * @param quesId
	 * @param pageable
	 * @param buildFilters
	 * @return
	 */
	public Page<Map> getRankingList(String quesId, Pageable pageable, String userName, String orgName){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select t.ranking, t.userName,t.account, t.orgName, t.orgNamePath,t.grade from (");
		sql.append(" select oqas.questionnaire_id id, oqas.status, oqas.ranking, u.user_name userName, u.login_name as account, o.org_name orgName,o.org_name_path as orgNamePath, oqas.grade");
		sql.append(" from oa_qusetionnaire_answer_status oqas");
		sql.append(" left join sys_user u on oqas.createdBy=u.id");
		sql.append(" left join sys_org o on oqas.createdOrg=o.id");
		sql.append(" ) t where t.id=:quesId and t.status='1'");
		if(StringUtils.isNotBlank(userName)){
            sql.append(" and t.userName like :userName");
            paramMap.put("userName", "%"+userName+"%");
        }
		if(StringUtils.isNotBlank(orgName)){
            sql.append(" and t.orgName like :orgName");
            paramMap.put("orgName", "%"+orgName+"%");
        }
		paramMap.put("quesId", quesId);
		List<PropertyFilter> buildFilters = new ArrayList<PropertyFilter>();
		String sqlStr = PropertyFilter.getSqlByFilterAndPageable("t", sql.toString(), "t.grade desc", buildFilters, pageable);
		Page<Map> page= this.findByPageNativeSQL(pageable, sqlStr, paramMap);
		List<Map>content=page.getContent();
		if(content!=null) {
			long offset=pageable.getOffset();
			long ranking=offset+1;
			for(Map ele:content) {
				ele.put("ranking",ranking++);
			}
		}
		return page;
	}
	
	/**
	 * 获取成绩排名
	 * @param quesId
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<Map> getDingRankingList(String quesId, String page, String pageSize, String corpId, String token){
		int pageSizeInt = Integer.parseInt(pageSize);
		int start = (Integer.parseInt(page)-1)*pageSizeInt;
		Map<String,Object> paramMap = new HashMap<String,Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select t.ranking, t.userName, t.orgName, t.grade, t.createdBy from (");
		sql.append(" select oqas.questionnaire_id id, oqas.status, oqas.ranking, oqas.createdBy, u.user_name userName, o.org_name orgName, oqas.grade");
		sql.append(" from oa_qusetionnaire_answer_status oqas");
		sql.append(" left join sys_user u on oqas.createdBy=u.id");
		sql.append(" left join sys_org o on oqas.createdOrg=o.id");
		sql.append(" ) t where t.id=:quesId and t.status='1' order by t.ranking asc");
		paramMap.put("quesId", quesId);
		List<Map> list = super.findByListNativeQuery(sql.toString(),"", paramMap, start, pageSizeInt);
		if(CollectionUtils.isNotEmpty(list)) {
			String userIds = "";
			for(int i = 0; i < list.size(); i++) {
				if(i == list.size() - 1) userIds += list.get(i).get("createdBy");
				else userIds += list.get(i).get("createdBy") + ",";
			}
			Map<String, String> images = answerService.getImages(userIds, corpId, token);
			for(Map m : list){
				String image = images.get(m.get("createdBy"));
				if(StringUtils.isNotBlank(image)) m.put("image", image);
				else m.put("image", "");
			}
		} 
		return list;
	}
	
	/**
	 * 导出成绩
	 * @param paramMap
	 * @return
	 */
	public List<QuestionnaireRankingExport> getExportList(Map<String, String> paramMap){
		String quesId = ValidateUtils.filter(paramMap.get("quesId"));
		//先更新排名
		statusService.rankingByGrade(quesId);
		String userName = paramMap.get("userName");
		String orgName = paramMap.get("orgName");
		Map<String,Object> param = new HashMap<String,Object>();
		StringBuffer sql = new StringBuffer();
		sql.append("select t.ranking, t.userName, t.orgName, t.grade,t.account, t.orgNamePath from (");
		sql.append(" select oqas.questionnaire_id id, oqas.status, oqas.ranking, u.user_name userName, o.org_name orgName, u.login_name as account, o.org_name_path as orgNamePath, oqas.grade");
		sql.append(" from oa_qusetionnaire_answer_status oqas");
		sql.append(" left join sys_user u on oqas.createdBy=u.id");
		sql.append(" left join sys_org o on oqas.createdOrg=o.id");
		sql.append(" ) t where t.id=:quesId and t.status='1'");
		if(StringUtils.isNotBlank(userName)){
            sql.append(" and t.userName like :userName");
            param.put("userName", "%"+userName+"%");
        }
		if(StringUtils.isNotBlank(orgName)){
            sql.append(" and t.orgName like :orgName");
            param.put("orgName", "%"+orgName+"%");
        }
		sql.append(" order by t.ranking asc");
		param.put("quesId", quesId);
		List<Map> list = super.findByListNativeQuery(sql.toString(), "", param);
		List<QuestionnaireRankingExport> result = new ArrayList<QuestionnaireRankingExport>();
        if(list != null && list.size() > 0){
            for(int i = 0; i < list.size(); i++){
            	QuestionnaireRankingExport export = new QuestionnaireRankingExport();
                Map<String, Object> map = list.get(i);
                export.setRanking(StringUtils.null2String(map.get("ranking")));
                export.setAccount(StringUtils.null2String(map.get("account")));
                export.setUserName(StringUtils.null2String(map.get("userName")));
                export.setOrgNamePath(StringUtils.null2String(map.get("orgNamePath")));
                export.setGrade(StringUtils.null2String(map.get("grade")));
                result.add(export);
            }
        }
        return result;
	}
}
